package com.comtime.mybox;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Application;
import android.content.ContextWrapper;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.comtime.entity.MusicInfo;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MusicPlayer;
import com.comtime.utils.MySharedPreferences;
import com.comtime.view.MyDialog;

public class SelectVoiceActivity extends Activity implements
		OnItemClickListener, OnClickListener {
	Application application;
	MySharedPreferences sharedPreferences;

	int selectType = 0; // 1:low battery 2:lost wain 3:wrong pwd

	boolean selectCustom;

	List<MusicInfo> musicInfos = new ArrayList<MusicInfo>();
	ListView listview;

	String antilossMusicPath;

	MusicPlayer musicPlayer;

	MediaRecorder mediaRecorder;

	ImageButton btn_record;
	TextView tv_record_title;
	Button btn_cancel, btn_ok;

	LinearLayout record_view;

	private final String directory_name = "Customized_Audio_skp";// 录音文件保存目录

	boolean showDetail;
	int showingPosition = -1;

	int record_duration;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		selectType = getIntent().getIntExtra("selectType", 1);
		application = this.getApplication();
		sharedPreferences = MySharedPreferences.getInstance(this);
		if(selectType==1){
			antilossMusicPath=sharedPreferences.getLowBatteryWainVoicePath();
		}else if(selectType==2){
			antilossMusicPath=sharedPreferences.getLostDeviceWainVoicePath();
		}else if(selectType==3){
			antilossMusicPath=sharedPreferences.getWrongPwdWainVoicePath();
		}
		setContentView(R.layout.activity_selectvoice);
		musicPlayer = new MusicPlayer(this);

		setupViews();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		musicPlayer.stopPlay();
	}

	private void setupViews() {
		record_view = (LinearLayout) findViewById(R.id.record_view);

		TextView tv_title = (TextView) findViewById(R.id.tv_activity_title);
		tv_title.setText(R.string.music_select);

		btn_record = (ImageButton) findViewById(R.id.btn_record);
		btn_record.setOnClickListener(this);

		tv_record_title = (TextView) findViewById(R.id.tv_record_status);

		RelativeLayout btn_back = (RelativeLayout) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);

		listview = (ListView) findViewById(R.id.listview);
		listview.setOnItemClickListener(this);

		initRingstoneList(0);
		listview.setAdapter(adapter);

		RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup_select_music);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				musicPlayer.stopPlay();
				showDetail = false;
				showingPosition = -1;

				switch (checkedId) {
				case R.id.radio_system_music:
					selectCustom = false;
					record_view.setVisibility(View.GONE);
					initRingstoneList(0);
					break;
				case R.id.radio_custom_music:
					record_view.setVisibility(View.VISIBLE);
					selectCustom = true;
					initRingstoneList(1);
					break;
				default:
					break;
				}
				adapter.notifyDataSetChanged();
			}
		});
	}

	private void initRingstoneList(int type) {
		musicInfos.clear();

		if (type == 0) {// 系统铃声

			MusicInfo musicInfo = null;
			musicInfo = new MusicInfo("android.resource://" + getPackageName()
					+ "/" + R.raw.lost, getString(R.string.default_music));
			musicInfos.add(musicInfo);
			sharedPreferences.saveLostDeviceWainVoicePath(antilossMusicPath);


			RingtoneManager manager = new RingtoneManager(this);

			manager.setType(RingtoneManager.TYPE_ALL);

			Cursor cursor = manager.getCursor();

			List<String> titles = new ArrayList<String>();

			int count = cursor.getCount();
			cursor.moveToNext();
			for (int i = 0; i < count; i++) {
				if (cursor.moveToPosition(i)) {
					String title = cursor
							.getString(RingtoneManager.TITLE_COLUMN_INDEX);

					if (!titles.contains(title)) {
						titles.add(title);
						String path = cursor
								.getString(RingtoneManager.URI_COLUMN_INDEX)
								+ "/"
								+ cursor.getString(RingtoneManager.ID_COLUMN_INDEX);
						musicInfo = new MusicInfo(path, title);
						if (!musicInfos.contains(musicInfo)) {
							musicInfos.add(musicInfo);
						}
					}
				}
			}
		} else if (type == 1) {// 自定义铃声，录音
			File file = getDir(directory_name, ContextWrapper.MODE_PRIVATE);
			for (File itemFile : file.listFiles()) {

				// Log.e("", "File List  :" + itemFile.getName());
				MusicInfo musicInfo = new MusicInfo(itemFile.getAbsolutePath(),
						itemFile.getName());
				musicInfo.modifyTime = itemFile.lastModified();
				musicInfos.add(musicInfo);
			}

			if (musicInfos.size() < 2)
				return;
			// 排序
			for (int j = 0; j < musicInfos.size() - 1; j++) {
				for (int i = 0; i < musicInfos.size() - 1 - j; i++) {
					MusicInfo currentInfo = musicInfos.get(i);
					MusicInfo nextInfo = musicInfos.get(i + 1);
					if (currentInfo.modifyTime < nextInfo.modifyTime) {
						musicInfos.set(i + 1, currentInfo);
						musicInfos.set(i, nextInfo);
					}
				}
			}

		}                              
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long arg3) {

		Log.e("", "点击  position: " + position);

		showDetail = false;
		showingPosition = -1;

		String musicPathString = musicInfos.get(position).path;
		musicPlayer.playWithPath(musicPathString);
		antilossMusicPath = musicPathString;
		if(selectType==1){
			//low battery
			sharedPreferences.saveLowBatteryWainVoicePath(antilossMusicPath);
			sharedPreferences
			.saveLowBatteryWainVoiceTitle(musicInfos.get(position).title);

		}else if(selectType==2){
			// TODO: 2017/8/24

			sharedPreferences.saveLostDeviceWainVoicePath(antilossMusicPath);
			sharedPreferences
			.saveLostDeviceWainVoiceTitle(musicInfos.get(position).title);

		}else if(selectType==3){
			sharedPreferences.saveWrongPwdWainVoicePath(antilossMusicPath);
			sharedPreferences
			.saveWrongPwdWainVoiceTitle(musicInfos.get(position).title);

		}

		
		adapter.notifyDataSetChanged();
	}

	private BaseAdapter adapter = new BaseAdapter() {

		private final int TYPE_MUSIC_INFO = 0;
		private final int TYPE_MUSIC_Custom = 1;
		private final int TYPE_MUSIC_Detail = 2;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder_Type_0 viewHolder_0 = null;
			ViewHolder_Type_1 viewHolder_1 = null;
			ViewHolder_Type_2 viewHolder_2 = null;
			int type = getItemViewType(position);

			if (convertView == null) {

				switch (type) {
				case TYPE_MUSIC_INFO:
					convertView = LayoutInflater.from(parent.getContext())
							.inflate(R.layout.list_item_musicinfo, null);
					viewHolder_0 = new ViewHolder_Type_0();
					viewHolder_0.tv_title = (TextView) convertView
							.findViewById(R.id.tv_music_title);
					viewHolder_0.image_selected = (ImageView) convertView
							.findViewById(R.id.image_selected);
					convertView.setTag(viewHolder_0);
					break;
				case TYPE_MUSIC_Custom:
					convertView = LayoutInflater.from(parent.getContext())
							.inflate(R.layout.list_item_custom_musicinfo, null);
					viewHolder_1 = new ViewHolder_Type_1();
					viewHolder_1.tv_title = (TextView) convertView
							.findViewById(R.id.tv_music_title);
					viewHolder_1.image_selected = (ImageView) convertView
							.findViewById(R.id.image_selected);
					viewHolder_1.tv_music_modify_time = (TextView) convertView
							.findViewById(R.id.tv_music_modify_time);
					viewHolder_1.btn_touch_down = (ImageButton) convertView
							.findViewById(R.id.btn_touch_down);
					convertView.setTag(viewHolder_1);

					break;
				case TYPE_MUSIC_Detail:
					convertView = LayoutInflater.from(parent.getContext())
							.inflate(R.layout.list_item_music_detail, null);
					viewHolder_2 = new ViewHolder_Type_2();
					viewHolder_2.edit_music_title = (EditText) convertView
							.findViewById(R.id.edit_music_title);
					viewHolder_2.tv_duration = (TextView) convertView
							.findViewById(R.id.tv_music_duration);
					viewHolder_2.tv_music_modify_time = (TextView) convertView
							.findViewById(R.id.tv_music_modify_time);
					viewHolder_2.btn_delete = (ImageButton) convertView
							.findViewById(R.id.btn_delete_record);

					convertView.setTag(viewHolder_2);
					break;
				}
			} else {
				switch (type) {
				case TYPE_MUSIC_INFO:
					viewHolder_0 = (ViewHolder_Type_0) convertView.getTag();
					break;
				case TYPE_MUSIC_Custom:
					viewHolder_1 = (ViewHolder_Type_1) convertView.getTag();
					break;
				case TYPE_MUSIC_Detail:
					viewHolder_2 = (ViewHolder_Type_2) convertView.getTag();
					break;
				}
			}

			switch (type) {
			case TYPE_MUSIC_INFO:
				viewHolder_0.tv_title.setText(musicInfos.get(position).title);

				if (musicInfos.get(position).path.equals(antilossMusicPath)) {
					viewHolder_0.image_selected.setVisibility(View.VISIBLE);
				} else {
					viewHolder_0.image_selected.setVisibility(View.INVISIBLE);
				}
				break;
			case TYPE_MUSIC_Custom:
				viewHolder_1 = (ViewHolder_Type_1) convertView.getTag();
				viewHolder_1.tv_music_modify_time.setText(formatTime(musicInfos
						.get(position).modifyTime));
				viewHolder_1.tv_title.setText(musicInfos.get(position).title);

				if (musicInfos.get(position).path.equals(antilossMusicPath)) {
					viewHolder_1.image_selected.setVisibility(View.VISIBLE);
				} else {
					viewHolder_1.image_selected.setVisibility(View.INVISIBLE);
				}

				viewHolder_1.btn_touch_down.setTag(position);
				viewHolder_1.btn_touch_down.setOnClickListener(clickListener);

				break;
			case TYPE_MUSIC_Detail:
				viewHolder_2 = (ViewHolder_Type_2) convertView.getTag();

				viewHolder_2.edit_music_title
						.setText(musicInfos.get(position).title);
				viewHolder_2.tv_music_modify_time.setText(formatTime(musicInfos
						.get(position).modifyTime));
				viewHolder_2.tv_duration.setText(String.format("%02d:%02d",
						(int) (record_duration / 60), (int) record_duration
								- (int) (record_duration / 60) * 60));

				viewHolder_2.btn_delete.setTag(position);
				viewHolder_2.btn_delete.setOnClickListener(clickListener);

				viewHolder_2.edit_music_title.setTag(position);
				viewHolder_2.edit_music_title
						.setOnEditorActionListener(editorActionListener);
				break;
			}

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return musicInfos.size();
		}

		@Override
		public int getItemViewType(int position) {
			if (selectCustom) {
				if (showDetail && showingPosition == position) {
					return TYPE_MUSIC_Detail;
				} else {
					return TYPE_MUSIC_Custom;
				}
			} else {
				return TYPE_MUSIC_INFO;
			}
		}

		@Override
		public int getViewTypeCount() {
			return 3;
		}

		class ViewHolder_Type_0 {
			TextView tv_title;
			ImageView image_selected;
		}

		class ViewHolder_Type_1 {
			TextView tv_title;
			ImageView image_selected;
			TextView tv_music_modify_time;
			ImageButton btn_touch_down;
		}

		class ViewHolder_Type_2 {
			EditText edit_music_title;
			TextView tv_music_modify_time;
			TextView tv_duration;
			ImageButton btn_delete;

		}

		OnClickListener clickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				int position = (Integer) v.getTag();
				switch (v.getId()) {
				case R.id.btn_touch_down:

					showDetail = true;
					showingPosition = position;

					record_duration = musicPlayer.playWithPath(musicInfos
							.get(position).path) / 1000;

					Log.e("", " touch down position:" + position);
					adapter.notifyDataSetChanged();

					break;
				case R.id.btn_delete_record:

					Log.e("", " delete position:" + position);
					showDeleteDialog(position);
					break;

				default:
					break;
				}
			}
		};
		OnEditorActionListener editorActionListener = new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				int position = (Integer) v.getTag();
				Log.e("", " rename position:" + position
						+ v.getText().toString());

				String oldTitle = musicInfos.get(position).title;

				if (oldTitle.equals(v.getText().toString()))
					return false;

				File directoryFile = getDir(directory_name,
						ContextWrapper.MODE_PRIVATE);

				File newfile = new File(directoryFile, v.getText().toString());

				if (newfile.exists()) {
					showCaution(getString(R.string.filename_exists));
				} else {
					File oldFile = new File(musicInfos.get(position).path);

					if (oldFile.renameTo(newfile)) {
						initRingstoneList(1);
					}
				}
				return false;
			}
		};

	};

	int recordState = 0;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			onBackPressed();
			break;
		case R.id.btn_record:
			Log.e("", "=======");
			showDetail = false;
			showingPosition = -1;
			if (recordState == 0) {
				tv_record_title.setText("00:00");
				startCountUp();
				recordState = 1;
				btn_record.setImageResource(R.drawable.image_record_stop);
				startRecord();
			} else if (recordState == 1) {
				recordState = 0;
				btn_record.setImageResource(R.drawable.image_record_start);
				stopRecord();
				stopCountUp();
				tv_record_title.setText(R.string.click_to_record);
				initRingstoneList(1);
				adapter.notifyDataSetChanged();
			}
			break;

		}
	}

	int totalTime;
	Timer timer;

	private void startCountUp() {
		if (timer != null) {
			timer.cancel();
		}
		timer = new Timer();
		totalTime = 0;
		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				totalTime++;
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						tv_record_title.setText(String.format("%02d:%02d",
								(int) (totalTime / 60), (int) totalTime
										- (int) (totalTime / 60) * 60));
					}
				});
			}
		};
		timer.scheduleAtFixedRate(timerTask, 1000, 1000);

	}

	private void stopCountUp() {
		if (timer != null) {
			timer.cancel();
		}
	}

	private void startRecord() {
		Log.e("", "点击添加 录音");
		if (mediaRecorder == null) {
			mediaRecorder = new MediaRecorder();
		}
		mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

		int customNum = sharedPreferences.getCustomRecordNum();

		String fileName = getString(R.string.new_record_) + customNum++;

		File directoryFile = getDir(directory_name, ContextWrapper.MODE_PRIVATE);

		File tempRecordFile = new File(directoryFile, fileName);

		while (tempRecordFile.exists()) {
			fileName = getString(R.string.new_record) + customNum++;
			tempRecordFile = new File(directoryFile, fileName);
		}

		sharedPreferences.saveCustomRecordNum(customNum);

		mediaRecorder.setOutputFile(tempRecordFile.getAbsolutePath());
		try {
			mediaRecorder.prepare();
		} catch (IllegalStateException e) {
		} catch (IOException e) {
		}
		mediaRecorder.start();

	}

	private void stopRecord() {
		Log.e("", "结束录音");
		mediaRecorder.stop();
		mediaRecorder.reset();
	}

	private String formatTime(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yy-MM-dd");
		return sDateFormat.format(time);
	}

	private void showDeleteDialog(final int position) {
		final MyDialog myDialog;
		myDialog = new MyDialog(this);
		myDialog.setContent(R.string.caution_delete_record);
		myDialog.setLeftButtonText(R.string.cancel);
		myDialog.setCancelable(false);
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.dismiss();
			}
		});

		myDialog.setRightButtonText(R.string.ok);
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.dismiss();

				File file = new File(musicInfos.get(position).path);
				if (file.exists()) {
					if (file.delete()) {
						if (showDetail && showingPosition == position) {

							antilossMusicPath = "android.resource://"
									+ getPackageName() + "/" + R.raw.bird;
							if(selectType==1){
								//low battery
								sharedPreferences.saveLowBatteryWainVoicePath(antilossMusicPath);
								sharedPreferences
								.saveLowBatteryWainVoiceTitle(musicInfos.get(position).title);

							}else if(selectType==2){
								sharedPreferences.saveLostDeviceWainVoicePath(antilossMusicPath);
								sharedPreferences
								.saveLostDeviceWainVoiceTitle(musicInfos.get(position).title);

							}else if(selectType==3){
								sharedPreferences.saveWrongPwdWainVoicePath(antilossMusicPath);
								sharedPreferences
								.saveWrongPwdWainVoiceTitle(musicInfos.get(position).title);

							}
						}

						initRingstoneList(1);

						showingPosition = -1;
						adapter.notifyDataSetChanged();
					}
				}

			}
		});
		myDialog.show();

	}

	Toast cautionToast;

	protected void showCaution(String string) {
		stopShowInterimCaution();

		cautionToast = Toast.makeText(this, string, Toast.LENGTH_LONG);
		cautionToast.setGravity(Gravity.CENTER, 0, 0);
		cautionToast.show();
	}

	private void stopShowInterimCaution() {
		if (cautionToast != null) {
			cautionToast.cancel();
		}
	}

}
